import 'package:flutter/material.dart';
import 'dart:ui';
import 'package:dio/dio.dart';
import 'dart:convert';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:flutter_easyrefresh/material_footer.dart';
import 'package:flutter_easyrefresh/material_header.dart';
import 'package:flutter_yres/tool/Toast.dart';
import 'package:flutter_yres/tool/network/http_method.dart';
import 'package:flutter_yres/tool/network/http_url.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_swiper/flutter_swiper.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter_yres/model/shop/pdd_list.model.dart';
import 'package:flutter_yres/pages/shop/pdd_detail_page.dart';
import '../../tool/md5_sign.dart';
import './newPddList.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:flutter_yres/tool/AppSaveInfoUtil.dart';
import 'package:flutter_yres/tool/constant.dart';
import 'package:flutter_yres/tool/LoadingUtil.dart';

class NewPddHomePage extends StatefulWidget {
  NewPddHomePage({Key key}) : super(key: key);

  @override
  _NewPddHomePageState createState() => _NewPddHomePageState();
}

class _NewPddHomePageState extends State<NewPddHomePage> {
  EasyRefreshController _controller = new EasyRefreshController();
  List bannerData = []; //轮播图数组
  List<PddListModelData> shopData = []; //拼多多商品
  int page = 1;
  var search = '';
  double _listHeight = ScreenUtil.getInstance().setHeight(260); //单个列表高度

  @override
  Widget build(BuildContext context) {
    return Container(
      child: EasyRefresh(
        enableControlFinishRefresh: true,
        enableControlFinishLoad: true,
        controller: _controller,
        header: MaterialHeader(),
        footer: MaterialFooter(),
        child: CustomScrollView(
          slivers: <Widget>[
            SliverToBoxAdapter(
              child: Container(
                  child: Column(
                children: <Widget>[
                  _buildBanner(),
                  Container(
                    height: 10,
                  )
                ],
              )),
            ),
            SliverToBoxAdapter(
              child: Container(
                child: Column(
                  children: <Widget>[
                    Row(
                      children: <Widget>[
                        GestureDetector(
                          onTap: () {
                            Navigator.push(
                                context,
                                MaterialPageRoute(
                                    //导航打开新视图
                                    builder: (context) => NewPddList(
                                          title: '实时热销榜',
                                        )));
                          },
                          child: Container(
                            margin: EdgeInsets.only(
                                left: ScreenUtil.getInstance().setWidth(10)),
                            child: Image.asset(
                              'images/pdd_list_left.png',
                              width: (ScreenUtil.getInstance().setWidth(750) -
                                      3 *
                                          ScreenUtil.getInstance()
                                              .setWidth(10)) /
                                  2,
                            ),
                          ),
                        ),
                        GestureDetector(
                            onTap: () {
                              Navigator.push(
                                  context,
                                  MaterialPageRoute(
                                      //导航打开新视图
                                      builder: (context) => NewPddList(
                                            title: '实时收益榜',
                                          )));
                            },
                            child: Container(
                              margin: EdgeInsets.only(
                                  left: ScreenUtil.getInstance().setWidth(10)),
                              child: Image.asset('images/pdd_list_right.png',
                                  width:
                                      (ScreenUtil.getInstance().setWidth(750) -
                                              3 *
                                                  ScreenUtil.getInstance()
                                                      .setWidth(10)) /
                                          2),
                            ))
                      ],
                    ),
                    Container(
                      margin: EdgeInsets.only(
                          bottom: ScreenUtil.getInstance().setWidth(20)),
                    ),
                    Row(
                      children: <Widget>[
                        GestureDetector(
                          onTap: () {
                            Navigator.push(
                                context,
                                MaterialPageRoute(
                                    //导航打开新视图
                                    builder: (context) => NewPddList(
                                          title: '1.9包邮',
                                        )));
                          },
                          child: Container(
                            margin: EdgeInsets.fromLTRB(
                                ScreenUtil.getInstance().setWidth(10),
                                0,
                                ScreenUtil.getInstance().setWidth(10),
                                0),
                            child: Image.asset(
                              'images/pdd_baoyou.png',
                              width: (ScreenUtil.getInstance().setWidth(750) -
                                      4 *
                                          ScreenUtil.getInstance()
                                              .setWidth(10)) /
                                  3,
                            ),
                          ),
                        ),
                        GestureDetector(
                          onTap: () {
                            Navigator.push(
                                context,
                                MaterialPageRoute(
                                    //导航打开新视图
                                    builder: (context) => NewPddList(
                                          title: '今日爆款',
                                        )));
                          },
                          child: Container(
                            margin: EdgeInsets.fromLTRB(
                                0, 0, ScreenUtil.getInstance().setWidth(10), 0),
                            child: Image.asset('images/pdd_baokuan.png',
                                width: (ScreenUtil.getInstance().setWidth(750) -
                                        4 *
                                            ScreenUtil.getInstance()
                                                .setWidth(10)) /
                                    3),
                          ),
                        ),
                        GestureDetector(
                            onTap: () {
                              Navigator.push(
                                  context,
                                  MaterialPageRoute(
                                      //导航打开新视图
                                      builder: (context) => NewPddList(
                                            title: '品牌清仓',
                                          )));
                            },
                            child: Container(
                              margin: EdgeInsets.fromLTRB(0, 0,
                                  ScreenUtil.getInstance().setWidth(10), 0),
                              child: Image.asset('images/pdd_pinpai.png',
                                  width:
                                      (ScreenUtil.getInstance().setWidth(750) -
                                              4 *
                                                  ScreenUtil.getInstance()
                                                      .setWidth(10)) /
                                          3),
                            )),
                      ],
                    ),
                    Container(
                      margin: EdgeInsets.only(
                          bottom: ScreenUtil.getInstance().setWidth(20)),
                    ),
                    Row(
                      children: <Widget>[
                        GestureDetector(
                          onTap: () {
                            getString(TOKEN).then((value) {
                              if (value == null || value == '') {
                                //未登陆
                                Navigator.of(context).pushNamed("login");
                              } else {
                                genrpprom('4', value);
                              }
                            });
                          },
                          child: Container(
                            child: Image.asset('images/pdd_card_top.png',
                                width:
                                    (ScreenUtil.getInstance().setWidth(750))),
                          ),
                        )
                      ],
                    ),
                    Container(
                        color: Colors.blue,
                        child: Column(
                          children: <Widget>[
                            Container(
                              margin: EdgeInsets.only(
                                  bottom:
                                      ScreenUtil.getInstance().setWidth(20)),
                            ),
                            Row(
                              children: <Widget>[
                                GestureDetector(
                                  onTap: () {
                                    getString(TOKEN).then((value) {
                                      if (value == null || value == '') {
                                        //未登陆
                                        Navigator.of(context)
                                            .pushNamed("login");
                                      } else {
                                        genrpprom('2', value);
                                      }
                                    });
                                  },
                                  child: Container(
                                    margin: EdgeInsets.fromLTRB(
                                        ScreenUtil.getInstance().setWidth(10),
                                        0,
                                        0,
                                        0),
                                    child: Image.asset('images/pdd_card_a.png',
                                        width: (ScreenUtil.getInstance()
                                                    .setWidth(750) -
                                                3 *
                                                    ScreenUtil.getInstance()
                                                        .setWidth(10)) /
                                            2),
                                  ),
                                ),
                                GestureDetector(
                                    onTap: () {
                                      getString(TOKEN).then((value) {
                                        if (value == null || value == '') {
                                          //未登陆
                                          Navigator.of(context)
                                              .pushNamed("login");
                                        } else {
                                          genrpprom('7', value);
                                        }
                                      });
                                    },
                                    child: Container(
                                      margin: EdgeInsets.fromLTRB(
                                          ScreenUtil.getInstance().setWidth(10),
                                          0,
                                          ScreenUtil.getInstance().setWidth(10),
                                          0),
                                      child: Image.asset(
                                          'images/pdd_card_b.png',
                                          width: (ScreenUtil.getInstance()
                                                      .setWidth(750) -
                                                  3 *
                                                      ScreenUtil.getInstance()
                                                          .setWidth(10)) /
                                              2),
                                    ))
                              ],
                            ),
                            Container(
                              margin: EdgeInsets.only(
                                  bottom:
                                      ScreenUtil.getInstance().setWidth(20)),
                            ),
                            Row(
                              children: <Widget>[
                                GestureDetector(
                                  onTap: () {
                                    getString(TOKEN).then((value) {
                                      if (value == null || value == '') {
                                        //未登陆
                                        Navigator.of(context)
                                            .pushNamed("login");
                                      } else {
                                        genrpprom('-1', value);
                                      }
                                    });
                                  },
                                  child: Container(
                                    margin: EdgeInsets.fromLTRB(
                                        ScreenUtil.getInstance().setWidth(10),
                                        0,
                                        0,
                                        0),
                                    child: Image.asset('images/pdd_card_c.png',
                                        width: (ScreenUtil.getInstance()
                                                    .setWidth(750) -
                                                3 *
                                                    ScreenUtil.getInstance()
                                                        .setWidth(10)) /
                                            2),
                                  ),
                                ),
                                GestureDetector(
                                    onTap: () {
                                      getString(TOKEN).then((value) {
                                        if (value == null || value == '') {
                                          //未登陆
                                          Navigator.of(context)
                                              .pushNamed("login");
                                        } else {
                                          genrpprom('0', value);
                                        }
                                      });
                                    },
                                    child: Container(
                                      margin: EdgeInsets.fromLTRB(
                                          ScreenUtil.getInstance().setWidth(10),
                                          0,
                                          ScreenUtil.getInstance().setWidth(10),
                                          0),
                                      child: Image.asset(
                                          'images/pdd_card_d.png',
                                          width: (ScreenUtil.getInstance()
                                                      .setWidth(750) -
                                                  3 *
                                                      ScreenUtil.getInstance()
                                                          .setWidth(10)) /
                                              2),
                                    ))
                              ],
                            ),
                            Container(
                              margin: EdgeInsets.only(
                                  bottom:
                                      ScreenUtil.getInstance().setWidth(20)),
                            ),
                            Row(
                              children: <Widget>[
                                GestureDetector(
                                  onTap: () {
                                    getString(TOKEN).then((value) {
                                      if (value == null || value == '') {
                                        //未登陆
                                        Navigator.of(context)
                                            .pushNamed("login");
                                      } else {
                                        genrpprom('3', value);
                                      }
                                    });
                                  },
                                  child: Container(
                                    margin: EdgeInsets.fromLTRB(
                                        ScreenUtil.getInstance().setWidth(10),
                                        0,
                                        0,
                                        0),
                                    child: Image.asset('images/pdd_card_e.png',
                                        width: (ScreenUtil.getInstance()
                                                    .setWidth(750) -
                                                3 *
                                                    ScreenUtil.getInstance()
                                                        .setWidth(10)) /
                                            2),
                                  ),
                                ),
                                GestureDetector(
                                    onTap: () {
                                      getString(TOKEN).then((value) {
                                        if (value == null || value == '') {
                                          //未登陆
                                          Navigator.of(context)
                                              .pushNamed("login");
                                        } else {
                                          genrpprom('5', value);
                                        }
                                      });
                                    },
                                    child: Container(
                                      margin: EdgeInsets.fromLTRB(
                                          ScreenUtil.getInstance().setWidth(10),
                                          0,
                                          ScreenUtil.getInstance().setWidth(10),
                                          0),
                                      child: Image.asset(
                                          'images/pdd_card_f.png',
                                          width: (ScreenUtil.getInstance()
                                                      .setWidth(750) -
                                                  3 *
                                                      ScreenUtil.getInstance()
                                                          .setWidth(10)) /
                                              2),
                                    )),
                              ],
                            ),
                            Container(
                              margin: EdgeInsets.only(
                                  bottom:
                                      ScreenUtil.getInstance().setWidth(20)),
                            ),
                          ],
                        )),
                    Container(
                      margin: EdgeInsets.only(
                          bottom: ScreenUtil.getInstance().setWidth(20)),
                    ),
                    Row(
                      children: <Widget>[
                        GestureDetector(
                          onTap: () {
                            getString(TOKEN).then((value) {
                              if (value == null || value == '') {
                                //未登陆
                                Navigator.of(context).pushNamed("login");
                              } else {
                                genResource('4', value);
                              }
                            });
                          },
                          child: Container(
                            margin: EdgeInsets.fromLTRB(
                                ScreenUtil.getInstance().setWidth(10),
                                0,
                                ScreenUtil.getInstance().setWidth(10),
                                0),
                            child: Image.asset('images/pdd_channel_a.png',
                                width: (ScreenUtil.getInstance().setWidth(750) -
                                        3 *
                                            ScreenUtil.getInstance()
                                                .setWidth(10)) /
                                    2),
                          ),
                        ),
                        Container(
                          child: Column(
                            children: <Widget>[
                              GestureDetector(
                                onTap: () {
                                  getString(TOKEN).then((value) {
                                    if (value == null || value == '') {
                                      //未登陆
                                      Navigator.of(context).pushNamed("login");
                                    } else {
                                      genResource('39996', value);
                                    }
                                  });
                                },
                                child: Container(
                                  child: Image.asset('images/pdd_channel_b.png',
                                      width: (ScreenUtil.getInstance()
                                                  .setWidth(750) -
                                              3 *
                                                  ScreenUtil.getInstance()
                                                      .setWidth(10)) /
                                          2),
                                ),
                              ),
                              Container(
                                margin: EdgeInsets.only(
                                    bottom:
                                        ScreenUtil.getInstance().setWidth(10)),
                              ),
                              Row(
                                children: <Widget>[
                                  GestureDetector(
                                    onTap: () {
                                      getString(TOKEN).then((value) {
                                        if (value == null || value == '') {
                                          //未登陆
                                          Navigator.of(context)
                                              .pushNamed("login");
                                        } else {
                                          genResource('39997', value);
                                        }
                                      });
                                    },
                                    child: Container(
                                      child: Image.asset(
                                          'images/pdd_channel_c.png',
                                          width: (((ScreenUtil.getInstance()
                                                              .setWidth(750) -
                                                          3 *
                                                              ScreenUtil
                                                                      .getInstance()
                                                                  .setWidth(
                                                                      10)) /
                                                      2) -
                                                  ScreenUtil.getInstance()
                                                      .setWidth(10)) /
                                              2),
                                    ),
                                  ),
                                  GestureDetector(
                                    onTap: () {
                                      getString(TOKEN).then((value) {
                                        if (value == null || value == '') {
                                          //未登陆
                                          Navigator.of(context)
                                              .pushNamed("login");
                                        } else {
                                          genResource('39999', value);
                                        }
                                      });
                                    },
                                    child: Container(
                                      margin: EdgeInsets.only(
                                          left: ScreenUtil.getInstance()
                                              .setWidth(10)),
                                      child: Image.asset(
                                          'images/pdd_channel_d.png',
                                          width: (((ScreenUtil.getInstance()
                                                              .setWidth(750) -
                                                          3 *
                                                              ScreenUtil
                                                                      .getInstance()
                                                                  .setWidth(
                                                                      10)) /
                                                      2) -
                                                  ScreenUtil.getInstance()
                                                      .setWidth(10)) /
                                              2),
                                    ),
                                  ),
                                ],
                              )
                            ],
                          ),
                        )
                      ],
                    )
                  ],
                ),
              ),
            ),
            SliverFixedExtentList(
                delegate: SliverChildBuilderDelegate(_buildListItem,
                    childCount: shopData.length),
                itemExtent: _listHeight),
          ],
        ),
        onRefresh: () async {
          page = 1;
          getPDDShopList();
        },
        onLoad: () async {
          page++;
          getPDDShopList();
        },
      ),
    );
  }

  //轮播图组件
  _buildBanner() {
    return new Container(
      margin: EdgeInsets.only(top: ScreenUtil.getInstance().setWidth(10)),
      width: ScreenUtil.getInstance().setWidth(750),
      height: ScreenUtil.getInstance().setWidth(750) * 0.4,
      child: Swiper(
        itemBuilder: _swiperBuilder,
        itemCount: bannerData.length,
        loop: false,
        autoplay: true,
        autoplayDelay: 15000,
        pagination: new SwiperPagination(
            builder: DotSwiperPaginationBuilder(
          color: Colors.black54,
          activeColor: Colors.white,
        )),
        scrollDirection: Axis.horizontal,
        onTap: (index) {
          print(bannerData[index]);
          Navigator.push(
              context,
              MaterialPageRoute(
                  //导航打开新视图
                  builder: (context) => NewPddList(
                        title: bannerData[index]['name'],
                        id: bannerData[index]['id'].toString(),
                      )));
        },
      ),
    );
  }

  Widget _swiperBuilder(BuildContext context, int index) {
    return CachedNetworkImage(
      width: ScreenUtil.getInstance().setWidth(750),
      height: ScreenUtil.getInstance().setWidth(750) * 0.4,
      fit: BoxFit.fill,
      imageUrl: bannerData[index]['image_url'],
      placeholder: (context, url) => Image.asset(
        'images/pic_default.png',
        fit: BoxFit.fill,
        width: ScreenUtil.getInstance().setWidth(750),
        height: ScreenUtil.getInstance().setWidth(750) * 0.4,
      ),
      errorWidget: (context, url, error) => Image.asset(
        'images/pic_default.png',
        width: ScreenUtil.getInstance().setWidth(750),
        height: ScreenUtil.getInstance().setWidth(750) * 0.4,
        fit: BoxFit.fill,
      ),
    );
  }

  Widget _buildListItem(BuildContext context, int index) {
    return new GestureDetector(
        onTap: () {
          //处理点击事件
          PddListModelData model = shopData[index];
          // var gasIds=model.gasid;
          Navigator.push(
              context,
              MaterialPageRoute(
                  //导航打开新视图
                  builder: (context) => PddShopDetailPage(
                      pddmodel: model) //打开第二个页面，并传值，传递值的名称是model
                  ));
        },
        child: Container(
            margin: EdgeInsets.fromLTRB(
                0, ScreenUtil.getInstance().setHeight(15), 0, 0),
            child: Column(
              children: <Widget>[
                Row(children: <Widget>[
                  _leftImage(index),
                  Expanded(
                    child: _rightColumn(index),
                  )
                ], crossAxisAlignment: CrossAxisAlignment.start),
                Divider(
                  height: 1,
                )
              ],
            )));
  }

  Widget _pd(Widget w, {double l, double t, double r, double b}) {
    //边距
    return Padding(
        padding: EdgeInsets.fromLTRB(
            ScreenUtil.getInstance().setWidth(l) ?? 0,
            ScreenUtil.getInstance().setHeight(t) ?? 0,
            ScreenUtil.getInstance().setWidth(r) ?? 0,
            ScreenUtil.getInstance().setHeight(b) ?? 0),
        child: w);
  }

  Widget _leftImage(int index) {
    PddListModelData model = shopData[index];
    //左图
    var image = CachedNetworkImage(
      width: ScreenUtil.getInstance().setHeight(180),
      height: ScreenUtil.getInstance().setHeight(180),
      fit: BoxFit.fill,
      imageUrl: model.goods_thumbnail_url,
      placeholder: (context, url) => Image.asset(
        'images/pic_default.png',
        width: ScreenUtil.getInstance().setHeight(180),
        height: ScreenUtil.getInstance().setHeight(180),
        fit: BoxFit.fill,
      ),
      errorWidget: (context, url, error) => Image.asset(
        'images/pic_default.png',
        width: ScreenUtil.getInstance().setHeight(180),
        height: ScreenUtil.getInstance().setHeight(180),
        fit: BoxFit.fill,
      ),
    );
    return _pd(image, l: 20, t: 0, r: 5, b: 40);
  }

  Widget _rightColumn(int index) {
    PddListModelData model = shopData[index];
    //右内容
    var title = Text(
      model.goods_name,
      style: TextStyle(
          color: Colors.black, fontSize: ScreenUtil.getInstance().setSp(26)),
      maxLines: 2,
      overflow: TextOverflow.ellipsis,
    );
    var price = RichText(
      text: TextSpan(style: TextStyle(color: Colors.red), children: [
        TextSpan(
            text: '¥',
            style: TextStyle(fontSize: ScreenUtil.getInstance().setSp(24))),
        TextSpan(
            text: (model.min_group_price / 100 - model.coupon_discount / 100)
                .toStringAsFixed(2),
            style: TextStyle(fontSize: ScreenUtil.getInstance().setSp(27))),
        TextSpan(
          text: (model.min_normal_price / 100).toStringAsFixed(2),
          style: TextStyle(
              fontSize: ScreenUtil.getInstance().setSp(22),
              color: Colors.grey,
              decoration: TextDecoration.lineThrough,
              decorationColor: Colors.grey),
        ),
      ]),
      maxLines: 1,
      overflow: TextOverflow.ellipsis,
    );
    var volume = Container(
      child: Text('销量' + model.sales_tip,
          style: TextStyle(
              color: Colors.grey,
              fontSize: ScreenUtil.getInstance().setSp(24))),
    );
    var quanHeader = Container(
      width: ScreenUtil.getInstance().setWidth(40),
      height: ScreenUtil.getInstance().setWidth(34),
      decoration: BoxDecoration(
        image: DecorationImage(
          image: AssetImage("images/item_youhuiquan_header.png"),
          fit: BoxFit.cover,
        ),
      ),
    );
    var quan = Container(
      width: ScreenUtil.getInstance().setWidth(70),
      height: ScreenUtil.getInstance().setWidth(34),
      decoration: BoxDecoration(
        image: DecorationImage(
          image: AssetImage("images/item_youhuiquan_footer.png"),
          fit: BoxFit.cover,
        ),
      ),
      child: Center(
          child: Text(
        (model.coupon_discount / 100).toString() + '元',
        style: TextStyle(
            color: Colors.white, fontSize: ScreenUtil.getInstance().setSp(24)),
      )),
    );
    var yongjin = Container(
      margin: EdgeInsets.fromLTRB(ScreenUtil.getInstance().setWidth(20), 0,
          ScreenUtil.getInstance().setWidth(20), 0),
      height: ScreenUtil.getInstance().setWidth(34),
      color: Color.fromRGBO(250, 226, 226, 1),
      child: Center(
          child: Text(
              '预估赚¥' +
                  (((model.min_group_price - model.coupon_discount) *
                              (model.promotion_rate / 1000)) /
                          100)
                      .toStringAsFixed(2),
              style: TextStyle(
                  color: Colors.red,
                  fontSize: ScreenUtil.getInstance().setSp(24)))),
    );
    return new Column(
      children: <Widget>[
        _pd(title, l: 10, t: 0, r: 10, b: 8),
        _pd(volume, l: 10, t: 0, r: 10, b: 8),
        _pd(price, l: 10, t: 0, r: 10, b: 8),
        Container(
          margin: EdgeInsets.all(ScreenUtil.getInstance().setWidth(5)),
          child: Row(
            children: <Widget>[
              Expanded(
                flex: 1,
                child: Row(
                  children: <Widget>[quanHeader, quan],
                ),
              ),
              Expanded(flex: 2, child: yongjin)
            ],
          ),
        )
        // Row(
        //   children: <Widget>[_pd(price, l: 10, t: 0, r: 10, b: 8), distance],
        // ),
        // _pd(address, l: 10, t: 0, r: 10, b: 8)
      ],
      crossAxisAlignment: CrossAxisAlignment.start,
    );
  }

  @override
  void initState() {
    getBannerList();
    getPDDShopList();
    super.initState();
  }

  getBannerList() async {
    FormData data = new FormData.fromMap(
        {'type': "pdd.ddk.goods.search", 'page_size': '15', 'page': '1'});
    Response<String> response =
        await HttpUtil().post(Api.getThemeList, data: data);
    Map userMap = json.decode(response.data);

    if (userMap['code'] == 1) {
      if (mounted) {
        print(userMap);
        setState(() {
          bannerData.clear();
          bannerData = userMap['data']['theme_list'];
        });
      }
    }
  }

  getPDDShopList() async {
    Map map = new Map();
    var timestamp = new DateTime.now().millisecondsSinceEpoch;
    map['type'] = 'pdd.ddk.goods.search';
    // map["sort_type"] = '';
    map["page"] = page;
    map["page_size"] = "10";
    map["cat_id"] = '0';
    map['timestamp'] = "$timestamp";
    map["client_id"] = '9cdd5d9fb8ee4d1b94a5f81d005a7922';
    map["data_type"] = "JSON";
    map["version"] = "V1";
    print(map);
    String key = '9a103e4e2cfc3b1ea51df0be47fb6e55e8497169';
    List<String> allKeys = [];
    map.forEach((key, value) {
      if (!(value is MultipartFile)) {
        allKeys.add(key.toString() + value.toString());
      }
    });
    allKeys.sort((obj1, obj2) {
      return obj1.compareTo(obj2);
    });
    String pairsString = allKeys.join("");
    print(pairsString);
    String sign = key + pairsString + key;
    String signString = generateMd5(sign).toUpperCase();
    map['sign'] = signString;

    // FormData data = new FormData.fromMap({'page': page, 'keyword': search});
    FormData data = FormData.fromMap(new Map<String, dynamic>.from(map));
    Response<String> response = await HttpUtil()
        .post("http://gw-api.pinduoduo.com/api/router?", data: data);
    Map userMap = json.decode(response.data);
    PddListModelEntity itemEntity = new PddListModelEntity.fromJson(userMap);
    print(userMap);
    // if (itemEntity.code == 0) {
    if (mounted) {
      setState(() {
        if (page == 1) {
          shopData.clear();
          shopData = itemEntity.data;
          _controller.finishRefresh();
        } else {
          shopData.addAll(itemEntity.data);
          _controller.finishLoad();
        }
      });
    }
    // }
  }

  genrpprom(String channel_type, String token) async {
    showDialog(
        context: context,
        barrierDismissible: false,
        builder: (_) {
          return new NetLoadingDialog(
            loadingText: "跳转中...",
            bgColor: Color.fromARGB(255, 0, 0, 0),
            requestCallBack: null,
            outsideDismiss: false,
          );
        });

    Map map = new Map();
    map["channel_type"] = channel_type;
    map["token"] = token;
    FormData data = FormData.fromMap(new Map<String, dynamic>.from(map));
    Response<String> response =
        await HttpUtil().post(Api.genRpPromUrl, data: data);
    Map userMap = json.decode(response.data);
    Navigator.of(context).pop(1);
    print(userMap);
    if (userMap['data'].containsKey('rp_promotion_url_generate_response')) {
      if (channel_type == "-1") {
      } else {
        String mobile_url = userMap['data']
            ['rp_promotion_url_generate_response']['url_list'][0]['mobile_url'];
        _openApp(mobile_url);
      }
    }
  }

  genResource(String resource_type, String token) async {
     showDialog(
        context: context,
        barrierDismissible: false,
        builder: (_) {
          return new NetLoadingDialog(
            loadingText: "跳转中...",
            bgColor: Color.fromARGB(255, 0, 0, 0),
            requestCallBack: null,
            outsideDismiss: false,
          );
        });
    Map map = new Map();
    map["resource_type"] = resource_type;
    map["token"] = token;
    FormData data = FormData.fromMap(new Map<String, dynamic>.from(map));
    Response<String> response =
        await HttpUtil().post(Api.genResourceUrl, data: data);
    Map userMap = json.decode(response.data);
    Navigator.of(context).pop(1);
    if (userMap['data'].containsKey('resource_url_response')) {
      String mobile_url = userMap['data']['resource_url_response']
          ['single_url_list']['mobile_url'];
      _openApp(mobile_url);
    }
  }

  void _openApp(openurl) async {
    // Android
    print("open app");
    final url = 'vnd.' + openurl;
    if (await canLaunch(url)) {
      await launch(url);
    } else {
      //  Ios
      final url = openurl;
      if (await canLaunch(url)) {
        await launch(url);
      } else {
        Toast.toast(context, msg: "打开失败");
        // throw 'Could not launch $url';
      }
    }
  }
}
